#include "button.h"
#include <QDebug>

static RegisterElementType r("Button", Button());

Button::Button()
{
    connect(this, &Button::keyEvent, this, &Button::onKeyEvent);
}

QString Button::type() const
{
    return "Button";
}

bool Button::copyFrom(const Element *e)
{
    const Button *b = qobject_cast<const Button*>(e);
    if(!b) return false;

    text_ = b->text_;
    return Element::copyFrom(b);
}

Element *Button::clone() const
{
    Button *b = new Button();
    if(!b->copyFrom(this)){
        delete b;
        b = NULL;
    }

    return b;
}

void Button::setText(const QString &text)
{
    text_ = text;
    setModified(true);
    emit appearanceChanged();
}

QString Button::text() const
{
    return text_;
}

QRect Button::sizeHint() const
{
    return QRect(rect_.x(), rect_.y(), text().length(), 1);
}

void Button::adjustSize()
{
    // Just adjust width
    int w = 0;
    for(QChar ch:text()){
        if(ch.unicode()>127){   // 中文
            w += 2;
        }else{
            w ++;
        }
    }
    if(w>width()){
        setWidth(w);
    }
    if(height()<=0){
        setHeight(1);
    }
}

void Button::paintEvent()
{
    writeText(rect(), text(), Color(color()), Color(background()));
}

void Button::onKeyEvent(int key, int value)
{
    if(!hasBindKey(key)){
        qWarning() << Q_FUNC_INFO << QString("Unknow key event (%1, %2)").arg(key).arg(value);
    }else{
        emit pressed();
        emit clicked();
    }
}

bool Button::prevUpdate()
{
    if(modified()){
        adjustSize();
        setModified(false);
    }
    return true;
}

QString Button::getSignalSignature(const QString &name) const
{
    if(name=="clicked"){
        return SIGNAL(clicked());
    }else{
        return Element::getSignalSignature(name);
    }
}
